package com.sgg.spzx.controller;

import cn.hutool.core.util.StrUtil;
import com.sgg.spzx.exception.CustomException;
import com.sgg.spzx.model.dto.system.LoginDto;
import com.sgg.spzx.model.entity.system.SysUser;
import com.sgg.spzx.model.vo.common.Result;
import com.sgg.spzx.model.vo.common.ResultCodeEnum;
import com.sgg.spzx.model.vo.system.LoginVo;
import com.sgg.spzx.model.vo.system.ValidateCodeVo;
import com.sgg.spzx.service.SysUserService;
import com.sgg.spzx.service.ValidateCodeService;
import com.sgg.spzx.utils.AuthContextUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

@Tag(name="用户接口")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ValidateCodeService validateCodeService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Operation(summary = "退出登录")
    @GetMapping("/logout")
    public Result logout(@RequestHeader(name="token")String token) {
        sysUserService.logout(token);
        return Result.build(null, ResultCodeEnum.SUCCESS);
    }

    @Operation(summary = "获取用户信息")
    @GetMapping("/getUserInfo")
    public Result getUserInfo(@RequestHeader(name="token") String token) {
//       SysUser sysUser = sysUserService.getUserInfo(token);
       return Result.build(AuthContextUtil.get(), ResultCodeEnum.SUCCESS);
    }

    @Operation(summary = "获取验证码")
    @GetMapping("/generateValidateCode")
    public Result<ValidateCodeVo> generateValidate() {
        ValidateCodeVo vo = validateCodeService.generateValidateCode();
        return Result.build(vo, ResultCodeEnum.SUCCESS);

    }

    @Operation(summary = "登录接口")
    @PostMapping("/login")
    public Result<LoginVo> login(@RequestBody LoginDto loginDto){
        String codeKey = loginDto.getCodeKey();
        String captcha = loginDto.getCaptcha();
        String str = stringRedisTemplate.opsForValue().get("user:validate" + codeKey);
        if (StrUtil.isEmpty(str) || !StrUtil.equalsIgnoreCase(str, captcha)) {
            throw new CustomException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        stringRedisTemplate.delete("user:validate" + codeKey);
        LoginVo loginVo = sysUserService.login(loginDto);
        return Result.build(loginVo, ResultCodeEnum.SUCCESS);
    }
}
